package com.zrx.app.android.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.zrx.app.android.R;
import com.zrx.app.android.UTIL.ZRXUTIL;
import com.zrx.app.android.modules.AuditModule;
import com.zrx.app.android.modules.CarDeliverModule;
import com.zrx.app.android.modules.LoanModule;
import com.zrx.app.android.modules.LoanReceiptModule;
import com.zrx.app.android.modules.SendedModule;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

public class ContentActivity extends BaseActivity {
   private static final String TAG = "ContengActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content);
        //findViewById(R.id.btnAudit).setOnClickListener((v)->ListActivity.startActivity(this));
        final ContentActivity self = this;
        findViewById(R.id.btnAudit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//全部按钮的点击事件
                ListContentActivity.startActivity(self,new AuditModule());  //Auditing审核
            }
        });//((v)->ListContentActivity.startActivity(this,new AuditModule()));
        findViewById(R.id.btnLoan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ListContentActivity.startActivity(self,new LoanModule());
            }
        });//((v)->ListContentActivity.startActivity(this, new LoanModule()));
        findViewById(R.id.btnReceipt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ListContentActivity.startActivity(self,new LoanReceiptModule());
            }
        });
        findViewById(R.id.btnCarDeliver).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ListContentActivity.startActivity(self,new CarDeliverModule());
            }
        });
        findViewById(R.id.btnCreditQuery).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CreditActivity.startActivity(self);
            }
        });//((v)->CreditActivity.startActivity(this));
        findViewById(R.id.btnBackend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                StringBuilder sb=new StringBuilder();
                File bgInfo=new File(ZRXUTIL.getPath()+"/bgInfo.txt");
                List<String> bgInfoList = readLastNLine(bgInfo, 20);
                if(bgInfoList!=null)
                    for(String str:bgInfoList)
                        sb.append(str+"\n");
                else
                    sb.append("没有信息");
                builder.setMessage(sb.toString());
                builder.setTitle("后台服务信息");
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });
        findViewById(R.id.btnCalTool).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CalculatorActivity.startActivity(self);
            }
        });
        findViewById(R.id.btnSended).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ListContentActivity_two.startActivity(self,new SendedModule());
            }
        });


        findViewById(R.id.btnClearAll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setMessage("这个操作会造成所有未提交或者未提交成功的资料(包括字段，照片和视频)将被删除，请谨慎使用！！！");
                builder.setTitle("警告信息");
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try{
                            deleteDir( new File(ZRXUTIL.getPath()));
                            new File(ZRXUTIL.getPath()+"/cache").mkdirs();
                        }catch (Exception e){}
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });

        findViewById(R.id.btnRepair).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setMessage("这个操作会造成未上传的字段信息被清除，但是未上传的照片和视频不会被删除，请谨慎使用！！！");
                builder.setTitle("警告信息");
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        try{
                            File rootDir = new File(ZRXUTIL.getPath());
                            File[] files = rootDir.listFiles();
                            for(int i=0;i<files.length;++i){
                                if(files[i].isDirectory()){
                                    File objFile = new File(files[i], "obj.json");
                                    if(objFile.exists()) {
                                        objFile.delete();

                                    }
                                }
                            }

//                            deleteDir( new File(ZRXUTIL.getPath()));
//                            new File(ZRXUTIL.getPath()+"/cache").mkdirs();
                        }catch (Exception e){}
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });
    }
    public static void startActivity(Context context) {
        Intent intent = new Intent(context,ContentActivity.class);
        context.startActivity(intent);
    }

    public static List<String> readLastNLine(File file, long numRead)
    {
        // 定义结果集
        List<String> result = new ArrayList<String>();
        //行数统计
        long count = 0;

        // 排除不可读状态
        if (!file.exists() || file.isDirectory() || !file.canRead())
        {
            return null;
        }

        // 使用随机读取
        RandomAccessFile fileRead = null;
        try
        {
            //使用读模式
            fileRead = new RandomAccessFile(file, "r");
            //读取文件长度
            long length = fileRead.length();
            //如果是0，代表是空文件，直接返回空结果
            if (length == 0L)
            {
                return result;
            }
            else
            {
                //初始化游标
                long pos = length - 1;
                while (pos > 0)
                {
                    pos--;
                    //开始读取
                    fileRead.seek(pos);
                    //如果读取到\n代表是读取到一行
                    if (fileRead.readByte() == '\n')
                    {
                        //使用readLine获取当前行
                        String line = new String(fileRead.readLine().getBytes("ISO-8859-1"),"utf-8");
                        //保存结果
                        result.add(line);

                        //打印当前行
                        System.out.println(line);

                        //行数统计，如果到达了numRead指定的行数，就跳出循环
                        count++;
                        if (count == numRead)
                        {
                            break;
                        }
                    }
                }
                if (pos == 0)
                {
                    fileRead.seek(0);
                    result.add(fileRead.readLine());
                }
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (fileRead != null)
            {
                try
                {
                    //关闭资源
                    fileRead.close();
                }
                catch (Exception e)
                {
                }
            }
        }

        return result;
    }

    @Override
    protected String getModuleName() {
        return null;
    }

    /**
     * 删除空目录
     * @param dir 将要删除的目录路径
     */
    private static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    public void click(View view){
        try {
            startActivity(new Intent(this,StagMoneyActivity.class));
        }catch (Exception e){
            Log.e(TAG,e.getMessage());
        }
    }
}
